
package ui;

import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Command;
import agent.*;
import manager.*;

public class ReceiveAgentScreen extends Form implements CommandListener {
	private manager.AgentManagerMIDlet midlet;
	private MeetingAgent agent;
	private Display display;
    private ChoiceGroup cgAgentTimes;
    private Command confirmCommand;
    private Command exitCommand;
	
	public ReceiveAgentScreen(AgentManagerMIDlet midlet, Display display, MeetingAgent agent){
		super("Please pick the times that suit you");
		this.midlet = midlet;
		this.display = display;
		this.agent = agent;
        cgAgentTimes = new ChoiceGroup("Which times are you available ? ", Choice.MULTIPLE);
        
        for(int i = 0 ; i < agent.sizeOfStartTimes(); i++){
        	cgAgentTimes.append("Starts at : " + agent.getStartTimes(i) +
        			"and finishes at : " +agent.getFinishTimes(i), null);
        }
        
        confirmCommand = new Command("Confirm", Command.SCREEN,1);
        exitCommand = new Command("Exit", Command.EXIT, 1);
        this.addCommand(exitCommand);
        this.addCommand(confirmCommand);
        this.append(cgAgentTimes);
        this.setCommandListener(this);
	}
	
	/**
	 * if user selects confirm, create an array the same size as
	 * the number of times. Fill this array from the choice group
	 * cgAgentTimes, and then for each value that is true, update
	 * the meeting agent.
	 * 
	 * lastly, send the agent to the next destination and return
	 * to the IdleScreen
	 */
	public void commandAction(Command c, Displayable d){
		if(c==exitCommand){
			midlet.exitRequested();
		}
		else if (c==confirmCommand){
			int size = agent.sizeOfStartTimes();
			int currentContactIndex = agent.getNextAddressIndex();			
			boolean choices[] = new boolean[size];
			
			for(int i = 0 ; i < size ; i++){
				choices[i] = cgAgentTimes.isSelected(i);
			}
			
			for(int i = 0 ; i < size ;i++){
				if(choices[i])
					agent.addAvailableTime(currentContactIndex, i);
			}
			
			midlet.getIOHandlerManager().sendAgent(agent);
			midlet.getUIHandlerManager().setIdleScreen();
		}
	}
}
